package io.plus.interactive.collections;

import drds.common.$;
import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.interactive.Configuration;
import io.plus.utils.lock.ReadWriteLockMap;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * 一对一  (businessId <--> AsynchronousSocketChannelContext)
 */
@Slf4j
public class BusinessIds {

    private ReadWriteLockMap<String, AsynchronousSocketChannelContext> businessIdToChannelContextMap = new ReadWriteLockMap<>(new HashMap<String, AsynchronousSocketChannelContext>());

    public void bind(String businessId, AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        if (asynchronousSocketChannelContext.clientConfiguration.isShortConnection) {
            return;
        }
        try {
            //先解绑，否则如果业务层绑定两个不同的bsid，就会导致资源释放不掉
            unbind(asynchronousSocketChannelContext);
            if ($.isNullOrEmpty(businessId)) {
                return;
            }
            asynchronousSocketChannelContext.setBusinessId(businessId);
            businessIdToChannelContextMap.put(businessId, asynchronousSocketChannelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    public void unbind(AsynchronousSocketChannelContext asynchronousSocketChannelContext) {
        Configuration configuration = asynchronousSocketChannelContext.clientConfiguration;
        if (configuration.isShortConnection) {
            return;
        }
        String businessId = asynchronousSocketChannelContext.getBusinessId();
        if ($.isNullOrEmpty(businessId)) {
            return;
        }
        try {
            businessIdToChannelContextMap.remove(businessId);
            asynchronousSocketChannelContext.setBusinessId(null);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    public ReadWriteLockMap<String, AsynchronousSocketChannelContext> getBusinessIdToChannelContextMap() {
        return businessIdToChannelContextMap;
    }

    public AsynchronousSocketChannelContext find(Configuration configuration, String businessId) {
        if (configuration.isShortConnection) {
            return null;
        }

        if ($.isNullOrEmpty(businessId)) {
            return null;
        }

        return businessIdToChannelContextMap.get(businessId);
    }
}
